package com.chunxuan.langquan.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.NewUserInfo;
import com.chunxuan.langquan.dao.bean.PwdLoginData;
import com.chunxuan.langquan.dao.bean.UserInfo;
import com.chunxuan.langquan.dao.bean.WxUserInfo1;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.ActiviceCollector;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.ui.listener.MyOrientationListener;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RegistActivity extends Base2Activity implements HandlerUtil.OnReceiveMessageListener{
    private AppCompatEditText et_phone, et_code, et_pwd,et_confirm_pwd;// 手机号，验证码，密码,确认密码
    private TextView tv_send_code, tv_ok, tv_privacy_policy, tv_service_agreement;// 发送验证码,注册，隐私政策，协议条款
    private CheckBox cb_check;
    private ImageView ivBack;
//
    private int LOGIN_TYPE = 0;// 0 普通登录 1 微信登录
    private WxUserInfo1 wxUserInfo;// 微信登录后解析的微信用户对象
    private Context context;

    private String phone, code, pwd,confirmPwd;
    private boolean isCd = false;// 是否正在倒计时
    private int currSecond = 60;// 当前倒计时的秒数
//
    private HandlerUtil.HandlerHolder handler = new HandlerUtil.HandlerHolder(this);

    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 20101951) {
            currSecond--;
            if (currSecond <= 0) {
                tv_send_code.setText("获取验证码");
                currSecond = 60;
                isCd = false;// 取消倒计时状态
            } else {
                tv_send_code.setText(currSecond + "秒");
                handler.sendEmptyMessageDelayed(20101951, 1000);
            }
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_regist;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        this.context = this;

        et_phone = findViewById(R.id.et_1);
        et_code = findViewById(R.id.et_2);
        et_pwd = findViewById(R.id.et_3);
        et_confirm_pwd=findViewById(R.id.et4);
        tv_send_code = findViewById(R.id.tv_send_sms);
        tv_privacy_policy = findViewById(R.id.tv_privacy_policy);
        tv_service_agreement = findViewById(R.id.tv_service_agreement);
        tv_ok = findViewById(R.id.tv_ok);
        cb_check = findViewById(R.id.cb_check);
        ivBack=findViewById(R.id.menu_back);
        setHeadTitle("");
        setOnClickListener(tv_send_code, tv_ok, tv_privacy_policy, tv_service_agreement,ivBack);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Arad.preferences.putBoolean("REGIST_BACK",true).flush();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_send_sms:
                if (!isCd) {
                    phone = et_phone.getText().toString().trim();
                    if (TextUtils.isEmpty(phone)) {
                        ToastUtils.showShort("请输入手机号");
                        return;
                    }
                    getMsgCode();
                    showProgress();
                    isCd = true;
                    handler.sendEmptyMessage(20101951);
                }
                break;
            case R.id.menu_back:
                Arad.preferences.putBoolean("REGIST_BACK",true).flush();
                finish();
                break;
            case R.id.tv_ok:
                phone = et_phone.getText().toString().trim();
                code = et_code.getText().toString().trim();
                pwd = et_pwd.getText().toString().trim();
                confirmPwd=et_confirm_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showShort("请输入验证码");
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    ToastUtils.showShort("请输入密码");
                    return;
                }
                if (TextUtils.isEmpty(confirmPwd)) {
                    ToastUtils.showShort("请再次输入密码");
                    return;
                }
                if(!pwd.equals(confirmPwd)){
                    ToastUtils.showShort("两次输入的密码不一致");
                    return;
                }
                if (!cb_check.isChecked()) {
                    ToastUtils.showShort("请阅读并同意《服务协议》和《隐私政策》");
                    return;
                }
                register();
                showProgress();
                break;
            case R.id.tv_privacy_policy:
                startActivity(PrivacyAgreeActivity.class);
                break;
            case R.id.tv_service_agreement:
                startActivity(UserAgreeActivity.class);
                break;
        }
    }

    public Disposable getMsgCode() {
        return APIRetrofit.getDefault().getMsgCode(phone,"register")
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        Logg.e("==发送短信验证码== " + baseResult2);
                        if (baseResult2.isSuccess()) {
                            ToastUtils.showShort(baseResult2.getMsg());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("发送失败，请重试");
                    }
                });
    }

    public Disposable register() {
        return APIRetrofit.getDefault().register(phone, pwd,confirmPwd,code)
                .compose(RxUtil.<BaseResult2<PwdLoginData>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<PwdLoginData>>() {
                    @Override
                    public void accept(BaseResult2<PwdLoginData> baseResult2) throws Exception {
                        hideProgress();
                        Logg.e("==注册账号== " + baseResult2);
                        if (baseResult2.isSuccess()) {
                            ToastUtils.showShort(baseResult2.getMsg());

                            Arad.preferences.putString(Config.USER_PREF_KEY, phone).flush();
                            Arad.preferences.putString(Config.PASSWORD_PREF_KEY, pwd).flush();
                            Global.HEADER=baseResult2.getData().getUserinfo().getToken();
                            Arad.preferences.putString(Config.GLOBAL_HEADER, baseResult2.getData().getUserinfo().getToken()).flush();

                            startActivity(GradeActivity.class);
                            finish();
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("注册失败，请重试");
                    }
                });
    }

}
